﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BskLeague.Models;

namespace BskLeague.Controllers
{
    public class PlayersController : Controller
    {
        BskLeagueDB _db = new BskLeagueDB();
/*****************************************************************/
        //Playing players list
        // GET: /Players/
        public ActionResult Index(char? letter, int? from, int? take)
        {
            @ViewBag.LettersList = IndexList();

            //parametry
            string l = (letter==null)? @ViewBag.Letterslist[0].ToString() : letter.ToString();
            from = (from != null) ? from : 0;
            take = (take != null) ? take : 5;
            @ViewBag.From = from;
            @ViewBag.Take = take;
            @ViewBag.Letter = letter;

            if (letter != '0')
            {
                @ViewBag.TotalItemsCount = _db.SeasonTeamPlayers
                    .Where(c => c.Player.PlayerSurname.StartsWith(l))
                    .OrderBy(p => p.Player.PlayerSurname).ToList()               //OrderBy is necessary here for items counting, otherwise LINQ claims Last() method's unsupported
                    .GroupBy(c => c.PlayerId).Select(grp => grp.Last())
                    .Count();

                var players = _db.SeasonTeamPlayers
                    .Where(p => p.Player.PlayerSurname.StartsWith(l))
                    .OrderBy(p => p.Player.PlayerSurname).ToList()
                    .GroupBy(p => p.PlayerId).Select(grp => grp.Last())    //last season only
                    .Skip((int)from)
                    .Take((int)take)
                    .Select(p => new
                    {
                        p.PlayerId,
                        PlayerName = p.Player.PlayerName + " " + p.Player.PlayerSurname,
                        LastSeasonStatus = p.Season.Status.Status,
                        LastSeasonName = p.Season.SeasonName,
                        p.Team.TeamName,
                        p.TeamId
                    });
                ViewBag.PlayerName = players.Select(p => p.PlayerName).ToList();
                ViewBag.PlayerID = players.Select(p => p.PlayerId).ToList();
                ViewBag.TeamName = players.Select(p => p.TeamName).ToList();
                ViewBag.TeamID = players.Select(p => p.TeamId).ToList();
                ViewBag.LastSeasonStatus = players.Select(p => p.LastSeasonStatus).ToList();
                ViewBag.LastSeasonName = players.Select(p => p.LastSeasonName).ToList();
            }
            else
            {
                @ViewBag.TotalItemsCount = _db.SeasonTeamPlayers
                .OrderBy(p => p.Player.PlayerSurname).ToList()
                .GroupBy(c => c.PlayerId).Select(grp => grp.Last())
                .Count();

                var players = _db.SeasonTeamPlayers
                    .OrderBy(p => p.Player.PlayerSurname).ToList()
                    .GroupBy(p => p.PlayerId).Select(grp => grp.Last())    //last season only
                    .Skip((int)from)
                    .Take((int)take)
                    .Select(p => new
                    {
                        p.PlayerId,
                        PlayerName = p.Player.PlayerName + " " + p.Player.PlayerSurname,
                        LastSeasonStatus = p.Season.Status.Status,
                        LastSeasonName = p.Season.SeasonName,
                        p.Team.TeamName,
                        p.TeamId
                    }).ToList();

                ViewBag.PlayerName = players.Select(p => p.PlayerName).ToList();
                ViewBag.PlayerID = players.Select(p => p.PlayerId).ToList();
                ViewBag.TeamName = players.Select(p => p.TeamName).ToList();
                ViewBag.TeamID = players.Select(p => p.TeamId).ToList();
                ViewBag.LastSeasonStatus = players.Select(p => p.LastSeasonStatus).ToList();
                ViewBag.LastSeasonName = players.Select(p => p.LastSeasonName).ToList();
            }



            return View();
        }
/*****************************************************************/
        //Details view of a single player
        // GET: /Players/Details/1
        public ActionResult Details(int id, int? take, int? from)
        {
           //parametry
           from = (from != null) ? from : 0;
           take = (take != null)? take: 5;
           @ViewBag.From = from;
           @ViewBag.Take = take;
           @ViewBag.Id = id;

           @ViewBag.TotalItemsCount = (from p in _db.Minutes
                                       where p.MinutesPlayed > 0 && p.Player.PlayerId == id
                                       select p.MinutesPlayed).Count();

           var player = _db.Players.Include("Licence").SingleOrDefault(p => p.PlayerId == id);
           
           //last matches
           var stats=_db.Minutes
               .Where(p=>p.MinutesPlayed>0 && p.Player.PlayerId==id)
               .OrderByDescending(p => p.Match.Date)
               .Skip((int)from)
               .Take((int)take)
               .Select(p=>new {p.MinutesPlayed,
                               p.Match.Date,
                               Team1=p.Match.Team1.TeamName,
                               Team1ID=p.Match.Team1.TeamId,
                               Team2=p.Match.Team2.TeamName,
                               Team2ID=p.Match.Team2.TeamId,
                               Season=p.Match.Season.SeasonName}).ToList();

            @ViewBag.Minutes=stats.Select(s=>s.MinutesPlayed).ToList();
            @ViewBag.Date=stats.Select(s=>s.Date.ToShortDateString()).ToList();
            @ViewBag.Team1Name=stats.Select(s=>s.Team1).ToList();
            @ViewBag.Team1ID=stats.Select(s=>s.Team1ID).ToList();
            @ViewBag.Team2Name=stats.Select(s=>s.Team2).ToList();
            @ViewBag.Team2ID=stats.Select(s=>s.Team2ID).ToList();
            @ViewBag.Season = stats.Select(s => s.Season).ToList();

            //last matches fauls
            @ViewBag.Fauls = _db.Fauls
                .Where(p => p.Player.PlayerId == id)
                .OrderBy(p => p.Match.Date)
                .Skip((int)from)
                .Take((int)take)
                .Select(p => p.FaulsCommited).ToList();

            //points gained in last matches
            var points = _db.Points
                .Where(p => p.Player.PlayerId == id)
                .OrderByDescending(p => p.Match.Date)
                .Skip((int)from)
                .Take((int)take)
                .Select(p => new { p.ScoredPoints, p.HalfTimeScoredPoints}).ToList();
            @ViewBag.PointsHalf=points.Select(p=>p.HalfTimeScoredPoints).ToList();
            @ViewBag.PointsTotal = points.Select(p => p.ScoredPoints).ToList();
            
            //last season played in
            var lastSeason=_db.SeasonTeamPlayers.Where(p=>p.PlayerId==id).OrderByDescending(s=>s.Season.SeasonName).First();
            @ViewBag.LastSeasonPlayedIn = lastSeason.Season.SeasonName;
            if (lastSeason != null)
            {
                @ViewBag.LastTeamID = lastSeason.Team.TeamId;
                @ViewBag.LastTeamName = lastSeason.Team.TeamName;
            }

            //Most scored poitns record
            var scoreRecords = _db.Points
                .Where(p => p.Player.PlayerId == id)
                .OrderByDescending(p => p.ScoredPoints)
                .Select(p=> new {p.ScoredPoints, p.Match.Season.SeasonName, TeamName1=p.Match.Team1.TeamName, TeamId1=p.Match.Team1.TeamId, TeamName2=p.Match.Team2.TeamName, TeamId2=p.Match.Team2.TeamId, Date = p.Match.Date}).First();
            @ViewBag.BestScorePoints = scoreRecords.ScoredPoints;
            @ViewBag.BestScoreSeason = scoreRecords.SeasonName;
            @ViewBag.BestScoreTeam1 = scoreRecords.TeamName1;
            @ViewBag.BestScoreTeamId1 = scoreRecords.TeamId1;
            @ViewBag.BestScoreTeam2 = scoreRecords.TeamName2;
            @ViewBag.BestScoreTeamId2 = scoreRecords.TeamId2;
            @ViewBag.BestScoreDate = scoreRecords.Date.ToShortDateString();
            
            //Most fauls commited record
            var faulRecords = _db.Fauls
                .Where(p => p.Player.PlayerId == id)
                .OrderByDescending(p => p.FaulsCommited)
                .Select(p => new { p.FaulsCommited, p.Match.Season.SeasonName, TeamName1 = p.Match.Team1.TeamName, TeamId1 = p.Match.Team1.TeamId, TeamName2 = p.Match.Team2.TeamName, TeamId2 = p.Match.Team2.TeamId, Date = p.Match.Date }).First();
            @ViewBag.MostFauls = faulRecords.FaulsCommited;
            @ViewBag.MostFaulsSeason = faulRecords.SeasonName;
            @ViewBag.MostFaulsTeam1 = faulRecords.TeamName1;
            @ViewBag.MostFaulsTeam2 = faulRecords.TeamName2;
            @ViewBag.MostFaulsTeamId1 = faulRecords.TeamId1;
            @ViewBag.MostFaulsTeamId2 = faulRecords.TeamId2;
            @ViewBag.MostFaulsSeason = faulRecords.SeasonName;
            @ViewBag.MostFaulsDate = faulRecords.Date.ToShortDateString();

            //Most minutes played record
            var minuteRecords = _db.Minutes
                .Where(p => p.Player.PlayerId == id)
                .OrderByDescending(p => p.MinutesPlayed)
                .Select(p => new { p.MinutesPlayed, p.Match.Season.SeasonName, TeamName1 = p.Match.Team1.TeamName, TeamId1 = p.Match.Team1.TeamId, TeamName2 = p.Match.Team2.TeamName, TeamId2 = p.Match.Team2.TeamId, Date = p.Match.Date }).First();
            @ViewBag.MostMinutes = minuteRecords.MinutesPlayed;
            @ViewBag.MostMinutesSeason = minuteRecords.SeasonName;
            @ViewBag.MostMinutesTeam1 = minuteRecords.TeamName1;
            @ViewBag.MostMinutesTeam2 = minuteRecords.TeamName2;
            @ViewBag.MostMinutesTeamId1 = minuteRecords.TeamId1;
            @ViewBag.MostMinutesTeamId2 = minuteRecords.TeamId2;
            @ViewBag.MostMinutesSeason = minuteRecords.SeasonName;
            @ViewBag.MostMinutesDate = minuteRecords.Date.ToShortDateString();

            //History of player's team
            var teamsHistory = _db.SeasonTeamPlayers
                .Where(p => p.Player.PlayerId == id)
                .OrderByDescending(p=> p.Season.SeasonName).ToList()
                .Select(p=> new {p.Season.SeasonName, p.Season.SeasonId, p.Team.TeamId, p.Team.TeamName})
                .ToList();
            @ViewBag.teamHistoryNames = teamsHistory.Select(p => p.TeamName).ToList();
            @ViewBag.teamHistoryIds = teamsHistory.Select(p => p.SeasonId).ToList();
            @ViewBag.teamHistorySeasons = teamsHistory.Select(p => p.SeasonName).ToList();
            return View(player);
        }

        /*****************************************************************/
        //lists of players names first letters
        private List<char> IndexList()
        {
            List<char> lista;
            lista = _db.Players
                .OrderBy(p => p.PlayerSurname).ToList()
                .GroupBy(p => p.PlayerSurname.Substring(0, 1).ToUpper())
                .Select(grp => grp.First())
                .Select(p => p.PlayerSurname[0])
                .ToList();
            return lista;
        }
    }
}
